package com.yeren.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.rmi.ServerException;
import java.util.Map;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.yeren.utils.AutoReplayUtil;
import com.yeren.utils.MessageUtil;
import com.yeren.utils.SignUtil;

/**
 * 微信核心处理类
 * 
 * @author liubiao
 *
 */
public class CoreServlet extends HttpServlet{
	/**
	 * 请求校验（确认请求来自微信服务器）
	 * @param request
	 * @param response
	 * @throws ServerException
	 * @throws IOException
	 */
	public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServerException,IOException{
		//微信加密签名
		String signature=request.getParameter("signature");
		//时间戳
		String timestamp=request.getParameter("timestamp");
		//随机数
		String nonce=request.getParameter("nonce");
		//随机字符串
		String echostr=request.getParameter("echostr");
		
		System.out.println("((((((((((((((((((((((((((((((((((((((");
		System.out.println("signature"+signature);
		System.out.println("timestamp"+timestamp);
		System.out.println("nonce"+nonce);
		System.out.println("echostr"+echostr);
		
		
		PrintWriter out=response.getWriter();
		//请求校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
		if(SignUtil.checkSignature(signature, timestamp, nonce)){
			System.out.println("++接入get成功++");
			out.print(echostr);
		}
		out.close();
		out=null;
	}
	
	/**
	 * 处理微信服务器发来的消息
	 */
	public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServerException,IOException{
		//将请求，响应的编码均设置为UTF-8(防止中文乱码)
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		//接收参数：微信加密签名，时间戳，随机数
		String signature=request.getParameter("signature");
		String timestamp=request.getParameter("timestamp");
		String nonce=request.getParameter("nonce");
		System.out.println("=====================================");
		System.out.println("signature:"+signature);
		System.out.println("timestamp:"+timestamp);
		System.out.println("nonce:"+nonce);
		PrintWriter out=response.getWriter();
		//请求校验
		if(SignUtil.checkSignature(signature, timestamp, nonce)){
			System.out.println("++接入post成功++");
			System.out.println("进入post===========>>>>>>>>>>>");
			//调用核心服务类接收处理请求
			String respXml=AutoReplayUtil.processRequest(request);
			System.out.println("respXml:"+respXml);
			out.print(respXml);
		}
		out.close();
		out=null;
	}
	
	
}
